package com.example.demohello.service.impl;

import com.example.demohello.entity.Todo;
import com.example.demohello.repo.TodoRepo;
import com.example.demohello.service.TodoService;
import org.hibernate.query.sqm.UnknownEntityException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TodoServiceImpl implements TodoService {

  private final TodoRepo todoRepo;

  public TodoServiceImpl(TodoRepo todoRepo) {
    this.todoRepo = todoRepo;
  }

  @Override
  public Todo createOne(Todo todo) {
    todo.setCreatedAt(LocalDateTime.now());
    todo.setUpdatedAt(todo.getCreatedAt());
    return todoRepo.save(todo);
  }

  @Override
  public Todo updateById(Integer id, Todo todo) {
    Todo entity = getById(id);
    entity.setTitle(todo.getTitle());
    entity.setCompleted(todo.getCompleted());
    entity.setUpdatedAt(LocalDateTime.now());
    return todoRepo.save(entity);
  }

  @Override
  public void removeById(Integer id) {
    Todo todo = getById(id);
    todoRepo.delete(todo);
  }

  @Override
  public Todo getById(Integer id) {
    return todoRepo.findById(id).orElseThrow(() -> new UnknownEntityException("Unknown todo: " + id));
  }

  @Override
  public List<Todo> listAll() {
    return todoRepo.findAll();
  }
}
